'use strict';

const http = require('http');
const cabctlConfig = require('../config.json').cabctlConfig;
const logger = require('./logutility').logger('cabutility');

/**
 * 开启快递柜
 * 
 * @param {string}portName 端口名称
 * @param {string}cmdOpen 开柜命令
 * @return {Promise}
 */
function openCab(portName, cmdOpen) {
    return new Promise((resolve, reject) => {
        let openUrl = `${cabctlConfig.url}operation=open&portName=${escape(portName)}&cmdOpen=${escape(cmdOpen)}`;
        let request = http.get(openUrl, function(res) {
            let data = '';
            res.on('data', (chunk) => data += chunk);
            res.on('end', function() {
                logger.info('Open Cab Response:' + data);
                if (res.statusCode === 200) {
                    if (data === '1') {
                        resolve(true);
                    } else {
                        resolve(false);
                    }
                } else {
                    resolve(false);
                }
            });
        });

        request.on('error', function(err) {
            reject(err);
        });

        request.setTimeout(500, function() {
            resolve("");
        });

        logger.info('Open Cab Url:' + openUrl);
    });
}

/**
 * 检测快递柜状态
 * 
 * @param {string}portName 端口名称
 * @param {string}cmdCheck 检测命令
 * @return {Promise}
 */
function checkCab(portName, cmdCheck) {
    return new Promise((resolve, reject) => {
        let checkUrl = `${cabctlConfig.url}operation=check&portName=${escape(portName)}&cmdCheck=${escape(cmdCheck)}`;
        let request = http.get(checkUrl, function(res) {
            let data = '';
            res.on('data', (chunk) => data += chunk);
            res.on('end', function() {
                logger.info('Check Cab Response:' + data);
                if (res.statusCode === 200) {
                    resolve(data);
                } else {
                    resolve("");
                }
            });
        });

        request.on('error', ()=>reject(err));
        request.setTimeout(500, ()=>resolve(""));

        logger.info('Check Cab Url:' + checkUrl);
    });
}

exports.openCab = openCab;
exports.checkCab = checkCab;